package com.example.ajaxdemo.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

public class MD5Encrypt {
	public static String byteArrayToString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToNumString(b[i]));
        }
        return resultSb.toString();
    }
 
    private static String byteToNumString(byte b) {
        int _b = b;
        if (_b < 0) {
            _b = 256 + _b;
        }
        return String.valueOf(_b);
    }
 
//  private static String byteToHexString(byte b) {
//      int n = b;
//      if (n < 0) {
//          n = 256 + n;
//      }
//      int d1 = n / 16;
//      int d2 = n % 16;
//      return hexDigits[d1] + hexDigits[d2];
//  }
 
    public static String MD5Encode(String origin) {
        System.out.println(getEncoding(origin));
        String resultString = null;
        try {
            resultString = new String(origin.getBytes("UTF-8"));
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToString(md.digest(resultString.getBytes()));
        } catch (Exception ex) {
 
        }
        return resultString;
    }
 
    public static void main(String[] args) throws UnsupportedEncodingException {
    	String res= "26broadband@125msg尊敬的用户你好！您的验证码是：184232，请保管好您的验证码！serviceNbr19909697263sign通信平台";

        System.out.println(MD5Encode(res));
    }


    public static String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是GB2312
                String s = encode;
                return s; //是的话，返回“GB2312“，以下代码同理
            }
        } catch (Exception exception) {
        }
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是ISO-8859-1
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是UTF-8
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是GBK
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return "";
    }
}
